package base

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

const (
	LOGNAME string = "log/Server.log"
)

func getProjectDirectory() string {
	if runtime.GOOS != "windows" {
		os.Chdir("../")
	}
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		fmt.Println("[getProjectDir] ", err)
	}
	logPath := dir + "/" + LOGNAME
	return strings.Replace(logPath, "\\", "/", -1)
}

func InitLogger() {
	logFilePath := getProjectDirectory()
	fmt.Println("logFilePath:", logFilePath)
	logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		logrus.Fatal(err)
	}
	defer logFile.Close()
	// 设置日志格式为JSON
	logrus.SetFormatter(&logrus.JSONFormatter{})

	// 设置日志输出到文件
	logrus.SetOutput(logFile)
	// 设置日志级别
	logrus.SetLevel(logrus.InfoLevel)
}
